<?php
namespace app\service;

use app\model\SendConfigModel;
use share\exception\ApiException;
use share\service\BaseModelService;

class SendConfigService extends BaseModelService{
    public static function getModel()
    {
        return new SendConfigModel;
    }

    public static function addConfig($item)
    {
        $origin = self::getByFilter(['appid' => $item['appid']]);
        if($origin){
            throw  new ApiException("appid:".$item['appid']." already exists! please check");
        }
        if(isset($item['ext'])){
            if(strlen($item['ext']) > 0){
                $ext = json_encode(json_decode($item['ext'],true));
                if($ext){
                    $item['ext'] = $ext;
                }
                else{
                    $item['ext'] = "";
                }
            }
            else{
                $item['ext'] = "";
            }
        }   
        return  self::add($item);
    }

    public static function updateConfig($id,$item)
    {
        $origin = self::getBase($id);
        if(!$origin){
            throw  new ApiException("data of id:{$id} is not exists! please check");
        }
        if($origin['appid'] != $item['appid']){
            $other = self::getByFilter(['appid' => $item['appid']]);
            if($other){
                throw  new ApiException("an other data of appid:".$item['appid']." already exists! please check");
            }
        }
        if(isset($item['ext'])){
            if(strlen($item['ext']) > 0){
                $ext = json_encode(json_decode($item['ext'],true));
                if($ext){
                    $item['ext'] = $ext;
                }
                else{
                    $item['ext'] = "";
                }
            }
            else{
                $item['ext'] = "";
            }
        }  
        return  self::update($id,$item);
    }


    public static function setConfig($param){
        $id =  $param['id'];
        unset($param['id']);
        if($id == 0){
            return self::addConfig($param);
        }
        else{
            return self::updateConfig($id,$param);
        }
    }

    public static function buildCondition($filter)
    {
        $res = [];
        if(isset($filter['appid']) && !empty($filter['appid'])){
            $res['appid'] = ['like','%'.$filter['appid'].'%'];
        }
        if(isset($filter['name']) && !empty($filter['name'])){
            $res['name'] = ['like','%'.$filter['name'].'%'];
        }
        if(isset($filter['type']) && !empty($filter['type'])){
            $res['type'] = $filter['type'];
        }
        return $res;
    }
}